package com.wisdudu.blank.ui.common;

import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.bigkoo.pickerview.adapter.ArrayWheelAdapter;
import com.bigkoo.pickerview.lib.WheelView;
import com.bigkoo.pickerview.listener.OnItemSelectedListener;
import com.orhanobut.logger.Logger;
import com.wisdudu.blank.R;
import com.wisdudu.blank.data.Injection;
import com.wisdudu.blank.data.repo.UserRepo;
import com.wisdudu.blank.data.source.remote.client.retrofit.subscribers.ProgressSubscriber;
import com.wisdudu.blank.data.source.remote.client.retrofit.subscribers.SubscriberOnNextListener;
import com.wisdudu.blank.databinding.FragmentSelectYmdBinding;
import com.wisdudu.frame.base.BaseFragment;
import com.wisdudu.blank.support.rxbus.RxBusFlag;
import com.wisdudu.blank.support.util.ToastUtil;
import com.wisdudu.blank.support.widget.loading.LoadingProgressDialog;
import com.wisdudu.frame.support.util.ComputeUtil;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Locale;

/**
 * Created by ypp on 2016/8/23.
 */
public class SelectYMDFragment extends BaseFragment {
    private static final String TAG = "SelectYMDFragment";
    WheelView mYearWheel;
    WheelView mMonthWheel;
    WheelView mDayWheel;
    private ArrayList<String> mYears;
    private int mCurrentMonthIndex;
    private int mCurrentYearIndex;
    private ArrayList<String> mMonths;
    private int yearFlag;//设置传入初始值 2016-09-26，26日修改思路：选择生日不超过当天日期
    private int monthFlag;
    private int dayFlag;
    private UserRepo userRepo;
    private int mCurrentYear;//设置当前日期的年月日 2016-09-26
    private int mCurrentMonth;
    private int mCurrentDay;
    private TextView tvAge;

    @Override
    protected View initBinding(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        FragmentSelectYmdBinding mBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_select_ymd, container, false);
        return mBinding.getRoot();
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        userRepo = Injection.provideUserRepo();
        if (!TextUtils.isEmpty(getArguments().getString(RxBusFlag.SELECT_YMD))) {
            String[] ymd = getArguments().getString(RxBusFlag.SELECT_YMD).split("-");
            if (ymd.length == 3) {
                yearFlag = Integer.parseInt(ymd[0]) - 1910;
                monthFlag = Integer.parseInt(ymd[1]) - 1;
                dayFlag = Integer.parseInt(ymd[2]) - 1;
            }
        }
        initToolbar(getToolbar(), "出生日期");
        mYearWheel = (WheelView) view.findViewById(R.id.yearWheel);
        mMonthWheel = (WheelView) view.findViewById(R.id.monthWheel);
        mDayWheel = (WheelView) view.findViewById(R.id.dayWheel);
        tvAge = (TextView) view.findViewById(R.id.tv_age);
        initCurrentYMD();
        initYear();
        initMonth();
        initDay();
        setAgeText();
    }

    private void setAgeText() {
        try {
            tvAge.setText(ComputeUtil.getAgeByBirthday(getBirthday()) + "");
        } catch (ParseException e) {
            e.printStackTrace();
            tvAge.setText("0");
        }
    }

    //计算当前年月日
    private void initCurrentYMD() {
        Calendar instance = Calendar.getInstance(Locale.CHINA);
        mCurrentYear = instance.get(Calendar.YEAR);
        mCurrentMonth = instance.get(Calendar.MONTH) + 1;
        mCurrentDay = instance.get(Calendar.DAY_OF_MONTH);
        Logger.d("当前年月日,%s,%s,%s", mCurrentYear, mCurrentMonth, mCurrentDay);
    }

    @Override
    protected void initMenuToolbar(Toolbar toolbar) {
        super.initMenuToolbar(toolbar);
        toolbar.inflateMenu(R.menu.menu_fragment_confirm);
        toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.menu_confirm:
                        confirm();
                        break;
                }
                return true;
            }
        });
    }

    private void confirm() {
        String birthday = getBirthday();
        if (getArguments().getInt(RxBusFlag.SELECT_YMD_FLAG, 0) == 1) {
            toFinish(birthday);
        } else {
            userRepo.editBirthday(birthday).compose(this.bindToLifecycle()).subscribe(new ProgressSubscriber<Object>(new SubscriberOnNextListener<Object>() {
                @Override
                public void onNext(Object o, LoadingProgressDialog pd) {
                    ToastUtil.INSTANCE.toast("修改成功");
                    toFinish(birthday);
                }
            }, mActivity));
//            userRepo.editUserInfo("birthday", birthday);
        }
    }

    @NonNull
    private String getBirthday() {
        int day = mDayWheel.getCurrentItem() + 1;
        String dayStr = day + "";
        if (day < 10) {
            dayStr = "0" + day;
        }
        return mYears.get(mCurrentYearIndex).replace("年", "").trim() + "-"
                + mMonths.get(mCurrentMonthIndex).replace("月", "").trim() + "-" + dayStr;
    }


    private void toFinish(String birthday) {
        Intent intent = new Intent();
        intent.putExtra(RxBusFlag.SELECT_YMD, birthday);
        getActivity().setResult(100, intent);
        getActivity().finish();
    }

    private void initDay() {
        ArrayList<String> days = getDays(1910 + yearFlag + "", monthFlag + 1 + "");
        if (days != null) {
            ArrayWheelAdapter<String> dayAdapter = new ArrayWheelAdapter<>(days, days.size());
            mDayWheel.setTextSize(18);
            mDayWheel.setCyclic(false);
            mDayWheel.setAdapter(dayAdapter);
            mDayWheel.setCurrentItem(dayFlag);
        }
    }

    private ArrayList<String> getDays(String year, String month) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
        Calendar calendar = new GregorianCalendar();
        int dayCount;
        try {

            Date date = sdf.parse(year + "-" + month);
            calendar.setTime(date);
            if (Integer.parseInt(year) == mCurrentYear && mCurrentMonth == Integer.parseInt(month)) {
                dayCount = mCurrentDay;
                mDayWheel.setCurrentItem(0);
            } else {
                dayCount = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
            }
            ArrayList<String> days = new ArrayList<>();
            for (int i = 1; i <= dayCount; i++) {
                String day;
                if (i < 10) {
                    day = "0" + i;
                } else {
                    day = "" + i;
                }
                days.add(day + "日");
            }
            return days;
        } catch (ParseException e) {
            e.printStackTrace();
            return null;
        }

    }


    private void initMonth() {
        mMonths = getMonths(mCurrentYear == 1910 + yearFlag);
        ArrayWheelAdapter<String> monthAdapter = new ArrayWheelAdapter<>(mMonths, mMonths.size());
        mMonthWheel.setTextSize(18);
        mMonthWheel.setCyclic(false);
        mMonthWheel.setCurrentItem(monthFlag);
        mCurrentMonthIndex = monthFlag;

        mMonthWheel.setOnItemSelectedListener(new OnItemSelectedListener() {
            @Override
            public void onItemSelected(int index) {
                mCurrentMonthIndex = index;
                mDayWheel.setAdapter(new ArrayWheelAdapter(getDays(mYears.get(mCurrentYearIndex).replace("年", "").trim(), mMonths.get(mCurrentMonthIndex).replace("月", "").trim())));
                setAgeText();
            }
        });
        mMonthWheel.setAdapter(monthAdapter);
    }

    private ArrayList<String> getMonths(boolean isCurrentYear) {
        ArrayList<String> months = new ArrayList<>();
        for (int i = 1; i <= (isCurrentYear ? mCurrentMonth : 12); i++) {
            String month;
            if (i < 10) {
                month = "0" + i;
            } else {
                month = i + "";
            }
            months.add(month + "月");
        }
        return months;
    }


    private void initYear() {
        mYears = getYears();
        ArrayWheelAdapter<String> yearAdapter = new ArrayWheelAdapter<>(mYears, mYears.size());
        mYearWheel.setTextSize(18);
        mYearWheel.setCyclic(false);
        mYearWheel.setAdapter(yearAdapter);
        mYearWheel.setCurrentItem(yearFlag);
        mCurrentYearIndex = yearFlag;
        mYearWheel.setOnItemSelectedListener(new OnItemSelectedListener() {
            @Override
            public void onItemSelected(int index) {
                mCurrentYearIndex = index;
                if (mCurrentYear == Integer.parseInt(mYears.get(mCurrentYearIndex).replace("年", "").trim())) {
                    mMonths.clear();
                    mMonths.addAll(getMonths(true));
                    mMonthWheel.setAdapter(new ArrayWheelAdapter(mMonths));
                    mMonthWheel.setCurrentItem(0);
                    mCurrentMonthIndex = 0;
                } else {
                    mMonths.clear();
                    mMonths.addAll(getMonths(false));
                    mMonthWheel.setAdapter(new ArrayWheelAdapter(mMonths));
                }
                mDayWheel.setAdapter(new ArrayWheelAdapter(getDays(mYears.get(mCurrentYearIndex).replace("年", "").trim(), mMonths.get(mCurrentMonthIndex).replace("月", "").trim())));
                setAgeText();
            }
        });
    }


    private ArrayList<String> getYears() {
//        SimpleDateFormat timeDf = new SimpleDateFormat("yyyy");
//        String format = timeDf.format(new Date());
//        int currentYear = Integer.parseInt(format);
        ArrayList<String> years = new ArrayList<>();
        for (int i = 1910; i <= mCurrentYear; i++) {
            years.add(i + "年");
        }
        return years;
    }
}
